package com.gg.communication.communication.tcp;

/**
 * @author sakura
 * @since 2025-06-16
 */

import com.gg.communication.communication.BaseCommunication;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.util.Map;

/**
 * @author sakura
 * @since 2025-06-16
 */
public class TcpClient extends BaseCommunication {
    private static final Map<String, TcpClient> tcpClientMap = new java.util.HashMap<>();
    private Socket socket;
    private InputStream inputStream;
    private OutputStream outputStream;

    private TcpClient() {
    }

    public static BaseCommunication initInstance(String host, int port) {
        synchronized (TcpClient.class) {
            if (tcpClientMap.get(host + ":" + port) == null) {
                TcpClient tcpClient = new TcpClient();
                tcpClient.setHost(host);
                tcpClient.setPort(port);
                tcpClientMap.put(host + ":" + port, tcpClient);
            }
        }
        return tcpClientMap.get(host + ":" + port);
    }

    @Override
    protected void startCommunication() throws SocketException {
        try {
            socket = new Socket(getHost(), getPort());
            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();
            System.out.println("TCP client connected to " + getHost() + ":" + getPort());
        } catch (IOException e) {
            throw new SocketException("Connection failed: " + e.getMessage());
        }
    }

    @Override
    public void doCommunicationSend(byte[] msg, String host, int port) throws IOException {
        if (socket != null && !socket.isClosed()) {
            try {
                outputStream.write(msg);
                outputStream.flush();
            } catch (Exception e) {
                close();
            }
        } else {
            close();
            throw new IOException("Socket is closed");
        }
    }

    @Override
    public byte[] doReceive() throws Exception {
        byte[] buffer = new byte[1024];
        int bytesRead = inputStream.read(buffer);
        if (bytesRead == -1) {
            throw new IOException("Connection closed by server");
        }
        byte[] responseData = new byte[bytesRead];
        System.arraycopy(buffer, 0, responseData, 0, bytesRead);
        return responseData;
    }


    public void close() throws IOException {
        super.close();
        try {
            if (socket != null && !socket.isClosed()) {
                socket.close();
                System.out.println("Disconnected from server");
            }
            tcpClientMap.remove(getHost() + ":" + getPort());
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("Error disconnecting: " + e.getMessage());
        }
    }
}
